#include "backendthread.h"
#include "database.h"


BackendThread::BackendThread(int socketDescriptor)
{
    connection=new QTcpSocket(this);

    if(connection->setSocketDescriptor(socketDescriptor)) {
        connect(connection, SIGNAL(readyRead()),
                     this, SLOT(read()));
        qDebug()<<"opening connection";
    } else {
        qDebug()<<"opening connection failed";
    }
    connect(connection,SIGNAL(disconnected()),this,SLOT(deleteLater()));
    buffer=new QBuffer(&response);
    buffer->open(QIODevice::WriteOnly);
    out.setDevice(buffer);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint64)0; //placeholder for size do not forget
    blockSize=0;
}

void BackendThread::run() {
    if(!connection->isOpen()) {
        connection->open(QIODevice::ReadWrite);
    } else {
        qDebug()<<"connection is open";
    }
}

void BackendThread::read() {
    qDebug()<<"reading";
    QDataStream in(connection);
    in.setVersion(QDataStream::Qt_4_0);

     if (blockSize == 0) {
         if (connection->bytesAvailable() < (int)sizeof(quint64))
             return;

         in >> blockSize;
         qDebug()<<"awaiting block of size "<<QString::number(blockSize);
     } else {
         qDebug()<<"data"<<connection->bytesAvailable() <<blockSize;
     }
    qDebug()<<connection->bytesAvailable() <<blockSize;
     if (connection->bytesAvailable() < blockSize) {
         return;
     } else {
        qDebug()<<"got it all";
     }
    QByteArray res;
    in >>res;
    QString result(res);
    qDebug()<<result;
    QStringList list=result.split(QRegExp("( |\n)"));

    if(QString(list.at(0)).compare("list")==0) {
        qDebug()<<"begin listing";
        QList<MediaFile *> * files=Querier::getFilesOfType(list.at(1),"");
        QByteArray s;
        s+=(list.at(1)+" Listing\n");
        foreach(MediaFile * file,*files) {
            s+=(QString::number(file->mediaID)+"; "+file->shortName+"\n");
        }
        out<<s;
        delete files;
    } else if(list.at(0)=="details") {
        QList<MediaFile *> * files=Querier::getFilesOfType("","mediaID='"+list.at(1)+"'");
        qDebug()<<files;
        if(files) {
            MediaFile * mediaFile= files->at(0);
            QByteArray s;
            s+="fileInfo ";
            s+=QString::number(mediaFile->mediaID)+"; ";
            s+=mediaFile->artist+"; ";
            s+=mediaFile->description+"; ";
            s+=mediaFile->extension+"; ";
            s+=QString::number(mediaFile->folderID)+"; ";
            s+=mediaFile->shortName+"; ";
            s+=mediaFile->title;
            out<<s;
        }
    }else if (list.at(0)=="send") {
        qDebug()<<"returning file";
        QList<MediaFile *> * files=Querier::getFilesOfType("","mediaID='"+list.at(1)+"'");
        qDebug()<<files;
        if(files) {
            MediaFile * mediaFile= files->at(0);
            qDebug()<<mediaFile;
            QFile file((mediaFile->fileLocation+"/"+mediaFile->shortName));
            file.open(QIODevice::ReadOnly);
            qDebug()<<"file exists? "<<file.exists();
            QByteArray s=file.readAll();
            out<<(s);
            qDebug()<<"done reading";
        }
    } else if (list.at(0)=="GET") {
        QString mediaID=list.at(1);
        int index=mediaID.lastIndexOf(".")-1;
        if(index<0) {
            index=-1;
        }
        mediaID=mediaID.mid(1,index);
        qDebug()<<"media id is "<<mediaID;
        QList<MediaFile *> * files=Querier::getFilesOfType("","mediaID='"+mediaID+"'");
        qDebug()<<files;
        if(files&&files->size()>0) {
            MediaFile * mediaFile= files->at(0);
            QHttpResponseHeader header;

            response.clear();
            qDebug()<<mediaFile;
            QFile file((mediaFile->fileLocation+"/"+mediaFile->shortName));
            file.open(QIODevice::ReadOnly);
            qDebug()<<"file exists? "<<file.exists();
            //QTextStream out(connection);
            //out.setAutoDetectUnicode(true);;
            out<<"HTTP/1.0 200 Ok\r\n";
            //out<<"content-type: application/octet-stream\r\n";

            out<<"Content-Type: video/mp4\r\n";
            out<<"Content-Disposition: attachment; filename=test.mp4; modification-date=\"Wed, 3 Jun 2010 12:00:00 -0500\"\r\n";
            out<<"Last-Modified: Tue, 1 Jan 2010 01:00:01 GMT\r\n";
            out<<"Accept-Ranges: none\r\n";
            //out<<("Etag: \"media"+mediaID+"\"\r\n");
            out<<"Date: Tue, 1 Jun 2010 03:00:00 GMT\r\n";
            //out<<"Content-Encoding: token\r\n";
            out<<("Content-Transfer-Encoding: base64\r\n");
            out<<("Content-Length: "+QString::number(file.size())+"\r\n");//*/

            out<<"\r\n";
            /*char * character=new char [1];
            while(file.getChar(character)) {
                out<<character;
            }*/
            out<<(file.readAll().toBase64());
            qDebug()<<"done reading";
            //connection->write(response);
            //response.clear();
            //out << (quint64)0; //placeholder for size do not forget
        }


    }
    write();

}

void BackendThread::write() {
    if(connection->isOpen()&&response.size()>0) {
        out.device()->seek(0);
        out << (quint64)(response.size() - sizeof(quint64));
        connection->write(response);
        response.clear();
        blockSize=0;
        out.device()->seek(0);
        out<<(quint64)0;
    }
}
